package main

import (
	"changeme/wellgo"
	"changeme/welllog"
	"context"
	"fmt"

	"github.com/wailsapp/wails/v2/pkg/runtime"
)

// App struct
type App struct {
	ctx       context.Context
	obPointer *wellgo.Observer
}

// NewApp creates a new App application struct
func NewApp() *App {
	app := App{}

	// 创建监听实例
	obValue := wellgo.Observer{}
	app.obPointer = &obValue

	return &app
}

// startup is called when the app starts. The context is saved
// so we can call the runtime methods
// 前端创建之后调用，但在 index.html 加载之前调用
func (a *App) startup(ctx context.Context) {
	a.ctx = ctx

	welllog.InitLog(ctx)

	a.obPointer.StartCtx(ctx)

	key := "onListenOne"
	oneListen := runtime.EventsOn(ctx, key, func(optionalData ...interface{}) {
		welllog.Debug("这里是什么？？")
		welllog.Debugf("%v", optionalData)
		if (len(optionalData) <= 0) {
			// 无数据
			return
		}

		switch what := optionalData[0].(type) {
		case []interface{}:
			for _,a := range what {
				switch v := a.(type) {
				case string:
					welllog.Debugf("string: %s", v)
				case bool:
					welllog.Debugf("double: %v", v)
				case int:
					welllog.Debugf("int: %d", v)
				case int64:
					welllog.Debugf("int64: %d", v)
				case float64:
					welllog.Debugf("float: %f", v)
				case map[string]interface{}:
					welllog.Debugf("map: %s %f", v["name"], v["age"])
				default:
					welllog.Debugf("what: %v", v)
				}
			}
		default:
			welllog.Info("lalala")
		}
	})
	a.obPointer.CacheObserveFunc(oneListen, key)
}

// 前端加载完毕 index.html 及其资源后调用此回调
func (a *App) domReady(ctx context.Context) {

}

// 前端被销毁之后，应用程序终止之前，调用此回调
func (a *App) shutDown(ctx context.Context) {
	key := "onListenOne"
	runtime.EventsOff(a.ctx, key)
}

// 单击窗口关闭按钮或调用runtime.Quit即将退出应用程序时被调用. 返回 true 将导致应用程序继续，false 将继续正常关闭
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
	return false
}

// Greet returns a greeting for the given name
func (a *App) Greet(name string) string {
	return fmt.Sprintf("Hello %s, It's show time!", name)
}
